package com.test.task;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.test.dao.HibernateUtil;
import com.test.util.DateUtil;

public class ActiveStudentWorkerByjdbc implements Task{
	public final static int SIZE = 10000;
	public Object params;
	public Object parentThread;
	
	public ActiveStudentWorkerByjdbc(Object args1,Object args2){
		this.params = args1;
		this.parentThread = args2;
	}
	
	public void run() {
		execute();
	}
	
	public void closeJdbcConn(Connection conn,Statement s, ResultSet rs) throws SQLException{
		if(rs!=null)
			rs.close();
		if(s!=null)
			s.close();
		if(conn!=null)
			conn.close();
	}

	public void execute() {
		System.out.println(getTaskName()+"子线程任务开始；");
		Long beginTime = System.currentTimeMillis(); 
		Integer round = (Integer)params;
		try {
			Connection conn = HibernateUtil.getSessionFactory().openSession().connection();
			PreparedStatement pst;
			System.out.println(getTaskName()+"子线程将查询修改："+round*SIZE+"行开始"+SIZE+"行数据");
			String sql = "select id from student where status='1' and activeTime is null  LIMIT ?,? ";
			pst = conn.prepareStatement(sql);
			pst.setInt(1, round*SIZE);
			pst.setInt(2, SIZE);
			ResultSet rs = pst.executeQuery();
			
			String _sql = "update student set activeTime = ?,activeFrom = ? where id = ? ";
			Connection _conn = HibernateUtil.getSessionFactory().openSession().connection();
			PreparedStatement _pst=_conn.prepareStatement(_sql);
			//设置手动提交
			_conn.setAutoCommit(false);
			while(rs.next()){
				String id =  rs.getString(1);
				_pst.setString(1, DateUtil.getCurrentTime());
				_pst.setString(2, "JDBC");
				_pst.setString(3, id);
				_pst.execute();
			}
			_conn.commit();
			closeJdbcConn(_conn,_pst,null);
			closeJdbcConn(conn,pst,rs);
			Long endTime = System.currentTimeMillis(); 
			System.out.println(getTaskName()+"执行完毕耗时"+(endTime-beginTime)+"毫秒，"+(endTime-beginTime)/1000+"秒，准备回调父任务");
			((ActiveStudentTask)parentThread).childCallBack(round);
			System.out.println(getTaskName()+"回调成功，子任务结束");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public String getTaskName() {
		return "Task[ActiveStudentTask[ActiveStudentWorkerByjdbc#"+params+"]]";
	}

}
